package com.changgou.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLock {

    @Autowired
    private RedisTemplate redisTemplate;

    // 默认锁过期时间
    public static final long DEFAULT_EXPIRE = 60;

    // 解锁脚本
    public static final String UNLOCK_SCRIPT = "if redis.call('get',KEYS[1]) == ARGV(1) then return redis.call('del',KEYS[1]) else return 0 end";


    /***
    *@Description
    *@Param
     * @param key   锁的key
     * @param value   随机值UUID 防止业务超时 删错锁
     * @param expireTime 过期时间秒
    *@Return boolean
    *@Author feilx
    */
    public boolean lock(String key, String value, long expireTime){

        if(expireTime > 0){
            return redisTemplate.opsForValue().setIfAbsent(key,value,expireTime,TimeUnit.SECONDS);
        }else{
            return redisTemplate.opsForValue().setIfAbsent(key,value,DEFAULT_EXPIRE,TimeUnit.SECONDS);
        }

    }

    public boolean unLock(String key, String value){
        Long flag  = (Long) redisTemplate.execute(new DefaultRedisScript<Long>(UNLOCK_SCRIPT, Long.class), Arrays.asList(key), value);
        if(flag > 0){
            return true;
        }else{
            return false;
        }

    }





}
